package j.nawks.wx.api.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;

/**
 * 类反射工具
 * 
 * @author Nawks.J@Gmail.com
 * 
 */
public class ClassUtils {

	public static Object instance(String className) {
		Object obj = null;
		try {
			obj = Class.forName(className).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return obj;
	}

	public static Object instance(Class clazz) {
		Object obj = null;
		try {
			obj = clazz.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return obj;
	}

	public static List<Method> getAccessSetterMethods(Class<?> clazz) {
		List<Method> methods = new LinkedList<Method>();
		Method[] ms = clazz.getMethods();
		for (Method m : ms) {
			if (m.getName().startsWith("set") && isAccessable(m)) {
				methods.add(m);
			}
		}
		return methods;
	}

	public static boolean isAccessable(Method method) {
		return method != null && Modifier.isPublic(method.getModifiers())
				&& !method.isSynthetic();
	}

	public static List<Field> getFields(Class<?> clazz, boolean forceAccess) {
		List<Field> fields = new LinkedList<Field>();
		for (Class<?> cls = clazz; cls != null; cls = cls.getSuperclass()) {
			Field[] fds = cls.getDeclaredFields();
			for (Field fd : fds) {
				if (forceAccess) {
					fd.setAccessible(true);
				}
				fields.add(fd);
			}
		}
		return fields;
	}
}
